# 关联算法实现
# 可参考https://blog.csdn.net/small__roc/article/details/123308261

from mlxtend.preprocessing import TransactionEncoder
from mlxtend.frequent_patterns import apriori
from mlxtend.frequent_patterns import association_rules
import pandas as pd
import numpy as np

df = pd.read_excel(r'./data/附件.xlsx',header=None)
data = df.replace(to_replace="?", value=np.NaN)
data = data.dropna()
data = data.iloc[1:,1:]
df_arr = np.array(data)


# df_arr = [['苹果','香蕉','鸭梨'],
#         ['橘子','葡萄','苹果','哈密瓜','火龙果'],
#         ['香蕉','哈密瓜','火龙果','葡萄'],
#         ['橘子','橡胶'],
#         ['哈密瓜','鸭梨','葡萄']
#         ]


# 转换为算法可接受模型（布尔值）
te = TransactionEncoder()
df_tf = te.fit_transform(df_arr)
df = pd.DataFrame(df_tf, columns=te.columns_)

#设置支持度求频繁项集
frequent_itemsets = apriori(df,min_support=0.4,use_colnames= True)
#求关联规则,设置最小置信度为0.15
rules = association_rules(frequent_itemsets,metric = 'confidence',min_threshold = 0.15)
#设置最小提升度
rules = rules.drop(rules[rules.lift < 0.1].index)
#设置标题索引并打印结果
rules.rename(columns = {'antecedents':'from','consequents':'to','support':'sup','confidence':'conf'},inplace = True)
rules = rules[['from','to','sup','conf','lift']]
print(rules)
#rules为Dataframe格式，可根据自身需求存入文件



# import pandas as pd
# from mlxtend.preprocessing import TransactionEncoder
# from mlxtend.frequent_patterns import apriori, fpmax, fpgrowth

# """购物篮数据"""
# dataset = [['牛奶', '鸡蛋', '蛤蜊'],
#            ['牛奶', '苹果', '鸡蛋'],
#            ['面包', '土豆'],
#            ['牛奶', '苹果', '鸡蛋'],
#            ]

# """热编码数据才行"""
# te = TransactionEncoder()
# te_ary = te.fit(dataset).transform(dataset)
# df = pd.DataFrame(te_ary, columns=te.columns_)
# print(df.to_string())

# """表达方式"""
# res2 = fpgrowth(df, min_support=0.4, use_colnames=True)
# print(res2.to_string())

# from mlxtend.frequent_patterns import association_rules

# res = association_rules(res2, metric="confidence", min_threshold=0.5)

# print(res.to_string())
